package net.yebaihe.wc;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import net.yebaihe.sdk.HttpConnection;
import net.yebaihe.wc.DataMan.MSGTYPE;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost.OnTabChangeListener;

public class Friends extends StateMachine{

	private ArrayList<TextView> allTags=new ArrayList<TextView>();
	private ListView lstFirends;
	String currSql;
	private SQLiteDatabase listdb;

	public Handler friendImgHandler=new Handler(){
		public void handleMessage(Message message) {
     		switch (message.what) {
     		case HttpConnection.DID_START: {
     			break;
     		}
     		case HttpConnection.DID_SUCCEED: {
     			String path=(String) message.obj;
				Bitmap thumb=Bitmap.createScaledBitmap(BitmapFactory.decodeFile(path), 50, 50, true);
     			
     			//Bitmap thumb=ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(path), 50, 50);
     			try {
     				FileOutputStream out = new FileOutputStream(path+".thumb");
     				thumb.compress(Bitmap.CompressFormat.PNG, 90, out);
     				out.close();
     			} catch (Exception e) {
     				e.printStackTrace();
     			}
     			refreshFriends();
     			break;
     		}
     		}
		}
	};
	private ListView lstFriendAddBtns;
	private ListView lstFriendSearchResult;
	protected int selectNo;
	private LinearLayout layoutFriendList;

	
	class FriendSimpleCursorAdapter extends SimpleCursorAdapter{

		public FriendSimpleCursorAdapter(Friends friends, int itemdish, Cursor c,
				String[] strings, int[] is) {
			super(friends,itemdish,c,strings,is);
		}
		
		@Override  
		public void bindView(View view, Context context, Cursor cursor) {  
			super.bindView(view, context, cursor);
			ImageView img=(ImageView) view.findViewById(R.id.imagethumb);
			File f=new File(getLocalFriendPath(cursor.getInt(0)));
			if (f.exists()){
				img.setImageBitmap(BitmapFactory.decodeFile(f.getAbsolutePath()));
			}
			else{
				//TODO new HttpConnection(Friends.this, friendImgHandler).file(getUserThumbUrl(cursor.getLong(0)), getLocalFriendPath(cursor.getInt(0)));
			}
		}
	}

	
	@Override
	public void HandleMessage(MSGTYPE msgtype, boolean ret,
			HashMap<String, String> params) {
		super.HandleMessage(msgtype, ret, params);
	}

	public String getUserThumbUrl(long long1) {
		// TODO Auto-generated method stub
		return null;
	}

	public String getLocalFriendPath(int id) {
		String basedir=Environment.getExternalStorageDirectory()+"/weican/users/";
		File f=new File(basedir);
		if (!f.exists()) f.mkdirs();
		//Log.d("", basedir+id+".dat");
		return basedir+id+".dat";
	}

	@Override
	protected String getTopbarTitle() {
		return "我的好友";
	}

	private TextView addTag(String string, LinearLayout layoutScrollTop) {
		TextView t=new TextView(this);
		t.setText(string);
		t.setTag(string);
		t.setGravity(Gravity.CENTER);
		allTags.add(t);
		LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.FILL_PARENT);
		p.rightMargin=10;
		p.leftMargin=10;
		t.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				for (int i=0;i<allTags.size();i++){
					allTags.get(i).setBackgroundColor(0x00000000);
				}
				v.setBackgroundResource(R.drawable.slide_light);
				String l=v.getTag().toString();
				UserInfoData userinfo = MyHelper.get(Friends.this).getCurrUserInfoData(Friends.this.getWCAppContext().email);
				if (l.equals("全部")){
					currSql="select * from users where _id in (select touid from friends where fromuid="+userinfo._id+");";
				}
				else{
					currSql="select * from users where _id in (select touid from friends where fromuid="+userinfo._id+" and friendgroup='"+v.getTag().toString()+"');";
				}
				refreshFriends();
			}
		});
		layoutScrollTop.addView(t,p);
		return t;
	}

	@Override
	protected void prepareClient(View client) {
		listdb=MyHelper.get(this).getReadableDatabase();
		View btnFriendList=LayoutInflater.from(this).inflate(R.layout.btnfriendlist, null);
		View btnFriendAdd=LayoutInflater.from(this).inflate(R.layout.btnfriendadd, null);

		LinearLayout tab1=(LinearLayout)this.findViewById(R.id.tab1);
        layoutFriendList = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.layoutfriendlist, null);
		lstFirends=(ListView) layoutFriendList.findViewById(R.id.lstfriends);
        tab1.addView(layoutFriendList,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));      
        //refreshFriends();

		UserInfoData userinfo = MyHelper.get(this).getCurrUserInfoData(this.getWCAppContext().email);
		currSql="select * from users where _id in (select touid from friends where fromuid="+userinfo._id+");";
		refreshFriends();
		refreshFriendGroup(userinfo._id);
		
        LinearLayout tab2=(LinearLayout)this.findViewById(R.id.tab2);
        LinearLayout layoutFriendAdd = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.layoutfriendadd, null);
        lstFriendAddBtns=(ListView) layoutFriendAdd.findViewById(R.id.lstFriendAddBtns);
        lstFriendSearchResult=(ListView) layoutFriendAdd.findViewById(R.id.lstFriendSearchResult);
        tab2.addView(layoutFriendAdd,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));        
        refreshFriendAddBtns();
        lstFriendSearchResult.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				final UserInfoData userinfo = MyHelper.get(Friends.this).getCurrUserInfoData(arg3);
				LinearLayout l=new LinearLayout(Friends.this);
				l.setOrientation(LinearLayout.VERTICAL);
				TextView v=new TextView(Friends.this);
				v.setText("你确实要添加 "+userinfo.username+" ("+userinfo.email+")为好友吗？");
				l.addView(v);
				LinearLayout lsub=new LinearLayout(Friends.this);
				lsub.setOrientation(LinearLayout.HORIZONTAL);
				TextView grouphint=new TextView(Friends.this);
				grouphint.setText("好友分组：");
				lsub.addView(grouphint);
				final EditText t=new EditText(Friends.this);
				lsub.addView(t,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
				l.addView(lsub);
				final String []friendGroups={
						"朋友",	
						"同事",	
						"家人",	
						"同学",	
						"自定义",	
				};
				new AlertDialog.Builder(Friends.this).setTitle("请为好友 "+userinfo.username+" 选择分组")
					.setSingleChoiceItems(friendGroups, 0, new DialogInterface.OnClickListener(){
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (which!=4){
								addFriend(userinfo,friendGroups[which]);
							}
							else{
								final EditText t=new EditText(Friends.this);
								new AlertDialog.Builder(Friends.this).setTitle("请输入分组名称")
									.setView(t)
									.setPositiveButton("确定", new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											String group=t.getText().toString();
											if (group.length()<=0) group="默认";
											addFriend(userinfo,group);
										}
									}).create().show();
							}
							dialog.dismiss();
						}
					})
					.create().show();
			}
        });
	     		
        final TabHost tabHost;
        tabHost=(TabHost) client.findViewById(R.id.tabhost);
        tabHost.setup();
        tabHost.addTab(tabHost.newTabSpec("friendlist").setContent(R.id.tab1).setIndicator(btnFriendList));
        tabHost.addTab(tabHost.newTabSpec("friendadd").setContent(R.id.tab2).setIndicator(btnFriendAdd));
        tabHost.setOnTabChangedListener(new OnTabChangeListener(){
			@Override
			public void onTabChanged(String tabId) {
				if (tabId.equals("friendlist")){
					refreshFriends();
					UserInfoData userinfo = MyHelper.get(Friends.this).getCurrUserInfoData(getWCAppContext().email);
					refreshFriendGroup(userinfo._id);
				}
				else if (tabId.equals("friendadd")){
					if (lstFriendSearchResult.isShown()){
						lstFriendSearchResult.setVisibility(View.GONE);
						lstFriendAddBtns.setVisibility(View.VISIBLE);
					}
				}
			}
        });
        tabHost.setCurrentTab(0);
        
	}
	
	private void refreshFriendGroup(long _id) {
		SQLiteDatabase db = MyHelper.get(this).getReadableDatabase();
		if (db!=null){
			LinearLayout layoutScrollTop=(LinearLayout) layoutFriendList.findViewById(R.id.layoutScrollTop);
			layoutScrollTop.removeAllViews();
			TextView t=addTag("全部",layoutScrollTop);
			t.setBackgroundResource(R.drawable.slide_light);
			Cursor c=db.rawQuery("SELECT distinct friendgroup FROM friends where fromuid="+_id, null);
			if (c.moveToFirst()){
				do{
					addTag(c.getString(0),layoutScrollTop);
				}while (c.moveToNext());
			}
			c.close();
			db.close();
		}        
	}

	private void addFriend(UserInfoData userinfo, String group) {
		UserInfoData myinfo = MyHelper.get(this).getCurrUserInfoData(this.getWCAppContext().email);
		SQLiteDatabase db = MyHelper.get(this).getWritableDatabase();
		Cursor c=db.rawQuery("select * from friends where fromuid="+myinfo._id+" and touid="+userinfo._id, null);
		if (c.getCount()<=0){
			MyHelper.get(this).insertNotify(myinfo._id, userinfo._id, myinfo.username+" 已把您添加为好友。", 2, "");
			db.execSQL("insert into friends (fromuid,touid,timestamp,friendgroup) values ("+myinfo._id+","+userinfo._id+","+new Date().getTime()+",'"+group+"')");
		}
		c.close();
		c=db.rawQuery("select * from friends where fromuid="+userinfo._id+" and touid="+myinfo._id, null);
		if (c.getCount()<=0){
			db.execSQL("insert into friends (fromuid,touid,timestamp,friendgroup) values ("+userinfo._id+","+myinfo._id+","+new Date().getTime()+",'"+group+"')");
		}
		c.close();
		db.close();
		Toast.makeText(this, "操作成功！", Toast.LENGTH_SHORT).show();
	}	
	
	protected void onDestroy() {
        super.onDestroy();
        //cursor.close();  //我们在onCreate()中没有关闭游标，因为需要和ListView进行数据关联，关闭curosr，会导致List无数据，故在最后释放资源
        listdb.close(); //断开和数据库的连接，释放相关资源
    }
	
	private void refreshFriendAddBtns() {
		String idxBtnTitles[]={
				"附近",
				"手机通讯录",
				"搜索",
			};
		int idxBtnImages[]={
				R.drawable.fre1,
				R.drawable.fre2,
				R.drawable.fre3,
			};
		ArrayList<HashMap<String, Object>> meumList = new ArrayList<HashMap<String, Object>>(); 
		for(int i = 1;i < idxBtnTitles.length+1;i++) { 
			HashMap<String, Object> map = new HashMap<String, Object>(); 
			map.put("ItemText", idxBtnTitles[i-1]); 
			map.put("imghint", idxBtnImages[i-1]); 
			meumList.add(map); 
		} 
		SimpleAdapter saMenuItem = new SimpleAdapter(this, 
				meumList, //数据源 
				R.layout.itemfriendaddbtn, //xml实现 
				new String[]{"imghint","ItemText"}, //对应map的Key 
				new int[]{R.id.imghint, R.id.ItemText});  //对应R的Id 
		lstFriendAddBtns.setAdapter(saMenuItem);
		lstFriendAddBtns.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2){
				case 0:
					doSearchNearby();
					break;
				case 1:
					doSearchAddressBook();
					break;
				case 2:
					doSearch();
					break;
				}
			}
		});
	}

	protected void doSearch() {
		final EditText uname=new EditText(this);
		new AlertDialog.Builder(this).setIcon(R.drawable.icon).setTitle("搜索好友")
			.setView(uname)
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					String username=uname.getText().toString();
					doSearchByUsername(username);
				}
			})
			.setNegativeButton("取消", null).create().show();
	}

	protected void doSearchByUsername(String username) {
		lstFriendSearchResult.setVisibility(View.VISIBLE);
		lstFriendAddBtns.setVisibility(View.GONE);
		String sql="select * from users where username like '%"+username+"%' and email!='"+this.getWCAppContext().email+"'";
		refreshSearchUserList(sql);		
	}

	protected void doSearchAddressBook() {
		//Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);  
		//startActivityForResult(intent, 1); 
		UserInfoData myinfo = MyHelper.get(this).getCurrUserInfoData(this.getWCAppContext().email);
		Intent it = new Intent(Intent.ACTION_VIEW);    
		it.putExtra("sms_body", "用 微餐 可以协同点餐，还可享受额外折扣，简单实用，推荐你用一下，下载地址: http://m.weican.com/ 记得安装后加我: "+myinfo.username);    
		it.setType("vnd.android-dir/mms-sms");    
		startActivity(it);   
	}

	protected void doSearchNearby() {
		SQLiteDatabase db = MyHelper.get(this).getWritableDatabase();
		if (db!=null){
			Cursor c=db.rawQuery("SELECT * FROM users", null);
			if (c.moveToFirst()){
				do{
					double len=this.getWCAppContext().distance(this.getWCAppContext().getBestLat(), this.getWCAppContext().getBestLon(), 
							c.getDouble(5), c.getDouble(4), 'K');
					ContentValues initValues = new ContentValues();
					initValues.put("length",len);
					db.update("users", initValues, "_id="+c.getInt(0), null);
					//Toast.makeText(this, "user "+c.getString(1)+" "+len, Toast.LENGTH_SHORT).show();
				}while (c.moveToNext());
			}
			c.close();
			db.close();
		}
		
		lstFriendSearchResult.setVisibility(View.VISIBLE);
		lstFriendAddBtns.setVisibility(View.GONE);
		String sql="select * from users where length>=0 and length<10 and email!='"+this.getWCAppContext().email+"' order by length";
		refreshSearchUserList(sql);		
		
	}

	private void refreshSearchUserList(String sql) {
		if (listdb!=null){
			Cursor c=listdb.rawQuery(sql, null);
			startManagingCursor(c);
			ListAdapter listAdapter = new FriendSimpleCursorAdapter(this, R.layout.itemsearchuser,
					c,
					new String[]{"username"},
					new int[]{R.id.txtname});
			lstFriendSearchResult.setAdapter(listAdapter);
		}
	}

	@Override
	public void onBackPressed(){
		if (lstFriendSearchResult.isShown()){
			lstFriendSearchResult.setVisibility(View.GONE);
			lstFriendAddBtns.setVisibility(View.VISIBLE);
		}
		else{
			super.onBackPressed();
			getWCAppContext().inviteInFriends=false;
		}
	}
	
	private void refreshFriends() {
		if (listdb!=null){
			//UserInfoData userinfo = MyHelper.get(this).getCurrUserInfoData(this.getWCAppContext().email);
			Cursor c=listdb.rawQuery(currSql, null);
			startManagingCursor(c);
			ListAdapter listAdapter = new FriendSimpleCursorAdapter(this, R.layout.itemfriend,
					c,
					new String[]{"username"},
					new int[]{R.id.txtname});
			lstFirends.setAdapter(listAdapter);
			lstFirends.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long id) {
					if (getWCAppContext().inviteInFriends){
						doInvite(id);
					}
					else{
						doDelete(id);
					}
				}
			});
		}
	}

	protected void doInvite(long id) {
		final UserInfoData userdata = MyHelper.get(this).getCurrUserInfoData(id);
		final UserInfoData mydata = MyHelper.get(this).getCurrUserInfoData(getWCAppContext().email);
		new AlertDialog.Builder(this).setIcon(R.drawable.icon).setTitle("邀请好友").setMessage("是否邀请"+userdata.username+"参与聚餐?")
			.setPositiveButton("是", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					int sessionid=getWCAppContext().sessionid;									
					SQLiteDatabase db = MyHelper.get(Friends.this).getWritableDatabase();
					Cursor c=db.rawQuery("select * from sessionuser where uid="+userdata._id+" and sessionid="+sessionid, null);
					if (c.getCount()<=0){
						Toast.makeText(Friends.this, "已发出邀请！", Toast.LENGTH_SHORT).show();
						db.execSQL("insert into sessionuser (sessionid,uid,state) values ("+sessionid+","+userdata._id+",1)");
						Cursor r=db.rawQuery("select * from restaurants where _id in (select restaurant from sessions where _id="+sessionid+")", null);
						r.moveToFirst();
						MyHelper.get(Friends.this).insertNotify(mydata._id, userdata._id, mydata.username+" 邀请您在 "+r.getString(1)+" 聚餐", 1, ""+sessionid+","+r.getLong(0));
						r.close();
					}
					else{
						Toast.makeText(Friends.this, "不能重复发送邀请！", Toast.LENGTH_SHORT).show();
					}	              	 
					c.close();
					db.close();
				}
			}).setNegativeButton("否", null).create().show();
	}

	protected void doDelete(long id) {
		final long friendid=id;
		UserInfoData userinfo = MyHelper.get(Friends.this).getCurrUserInfoData(id);
		new AlertDialog.Builder(Friends.this).setIcon(R.drawable.icon)
		.setTitle("删除好友")
		.setMessage("您确定要删除好友 "+userinfo.username+"("+userinfo.email+")吗？")
		.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				SQLiteDatabase db = MyHelper.get(Friends.this).getWritableDatabase();
				if (db!=null){
					UserInfoData uinfo = MyHelper.get(Friends.this).getCurrUserInfoData(Friends.this.getWCAppContext().email);
					db.delete("friends", "fromuid="+uinfo._id+" and touid="+friendid, null);
					db.close();
					refreshFriends();
					refreshFriendGroup(uinfo._id);
				}
			}
		})
		.setNegativeButton("取消", null)
		.create().show();
	}

	@Override
	protected int getLayoutRes() {
		return R.layout.friends;
	}

	
	/*
	@Override  
	public void onActivityResult(int reqCode, int resultCode, Intent data) {  
	    super.onActivityResult(reqCode, resultCode, data);  
	    if (resultCode == Activity.RESULT_OK) {  
	        Uri contactData = data.getData();  
	        Cursor c =  managedQuery(contactData, null, null, null, null);  
	        if (c.moveToFirst()) {  
	            c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 
	            String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                final ArrayList<String>itemlist=new ArrayList<String>();
	            if (Integer.parseInt(c.getString(
	                    c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
	                 Cursor pCur = managedQuery(
	                 ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
	                 null, 
	                 ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
	                 new String[]{contactId}, null);
	                 while (pCur.moveToNext()) {
	                	 itemlist.add(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
	                 } 
	                 pCur.close();
	             }
                String[] items=new String[itemlist.size()];
                itemlist.toArray(items);
                if (items.length<=0){
                	Toast.makeText(this, "您选择的联系人似乎没有有效的联系号码！", Toast.LENGTH_LONG).show();
                	return;
                }
	            new AlertDialog.Builder(this).setIcon(R.drawable.icon).setTitle("请选择接收短信的号码")
	            	//.setMessage("您选择的联系人 "+name+" 还不是"+getString(R.string.app_name)+"用户，您要发送短信通知它吗？")
	            	//.setView(view)
	            	.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							SmsManager smsManager = SmsManager.getDefault();
			                PendingIntent sentIntent = PendingIntent.getBroadcast(Friends.this, 0, new Intent(), 0);
			                UserInfoData userinfo = MyHelper.get(Friends.this).getCurrUserInfoData(Friends.this.getWCAppContext().email);
			                String strContent="您的好友 "+userinfo.username+" 邀请您使用 "+getString(R.string.app_name)+" 并成为他/她的好友!";
			                String strNo=itemlist.get(selectNo);
			                if (strContent.length() > 70) {
			                    List<String> msgs = smsManager.divideMessage(strContent);
			                    for (String msg : msgs) {
			                        smsManager.sendTextMessage(strNo, null, msg, sentIntent, null);                        
			                    }
			                } else {
			                    smsManager.sendTextMessage(strNo, null, strContent, sentIntent, null);
			                }
			                Toast.makeText(Friends.this, "短信发送完成", Toast.LENGTH_LONG).show();
						}
					})
					.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int pos) {
							selectNo=pos;
						}
					  })
					.setNegativeButton("取消", null)
					.create().show();
	        }  
	    }  
	}*/	
	
}
